<template>
  <el-dialog
    top="30px"
    width="600px"
    class="dialog-sm"
    append-to-body
    title="保费登记"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <el-form :model="ruleForm" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="收取金额" prop="actual_warrant_fee">
        <el-input
          :min="0"
          type="number"
          v-model="ruleForm.actual_warrant_fee"
          placeholder="收取金额"
          style="width: 260px"
        >
          <template slot="append">万元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="缴费时间" prop="actual_warrant_date" class="form-control-ml">
        <el-date-picker
          type="date"
          class="w-100"
          value-format="yyyy-MM-dd"
          placeholder="收取时间"
          v-model="ruleForm.actual_warrant_date"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="备注" prop="remark" class="form-control-ml">
        <el-input type="textarea" :rows="3" v-model="ruleForm.remark"></el-input>
      </el-form-item>
      <el-form-item label="附件上传" class="w-100">
        <upload-oss
          multiple
          accept="image/*"
          list-type="picture-card"
          ref="attachOss"
          :file-list="attachFileList"
          :limit="10"
          :on-complete="handleImagesComplete"
        ></upload-oss>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" :loading="saveLoading" class="btn-long">
          登记
        </el-button>
        <el-button class="btn-long" @click="beforeClose" :disabled="saveLoading">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { arrayFromString, sub } from '@vimi/utils-tool'
import { strFromOss, num } from '@/common/plugins/tools/format'

export default {
  components: {},
  props: {
    visible: Boolean,
    editRow: {
      type: Object,
      default() {
        return {}
      },
    },
    collectRow: {
      type: Object,
      default() {
        return {}
      },
    },
    viewMode: Boolean,
  },
  data() {
    return {
      tableName: 'credit_warrant_fee_register',
      saveLoading: false,
      attachFileList: [],
      ruleForm: {
        actual_warrant_fee: '',
        actual_warrant_date: '',
      },
      rules: {
        actual_warrant_fee: [
          { required: true, message: '请输入收取金额', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              value = Number(value)
              if (value <= 0) {
                return callback(new Error('金额不能小于等于0'))
              }
              callback()
            },
            trigger: 'blur',
          },
        ],
        actual_warrant_date: [{ required: true, message: '请选择收取时间', trigger: 'change' }],
      },

      registerTotalFunds: 0,
    }
  },
  computed: {
    ...mapGetters(['user']),
    isFinanceUser() {
      return this.user.scopeArr.includes('financeO')
    },
    accountingFunds() {
      return num(this.collectRow.check_warranty_fee)
    },
    leftFunds() {
      return Math.max(sub(this.accountingFunds, this.registerTotalFunds), 0)
    },
  },
  watch: {
    editRow: {
      handler: function () {
        this.initForm()
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.$refs.form.clearValidate()
      this.$emit('update:visible', false)
    },
    initForm() {
      Object.keys(this.ruleForm).forEach(key => {
        this.ruleForm[key] = this.editRow[key] || ''
      })
      this.attachFileList = arrayFromString(this.editRow.attachment).map(img => ({
        name: '',
        url: img,
      }))

      this.getRegisterTotalFunds()
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (num(this.ruleForm.actual_warrant_fee) > num(this.leftFunds)) {
            this.$confirm(
              `累计登记金额（${this.registerTotalFunds || 0}+${
                this.ruleForm.actual_warrant_fee || 0
              }万元）已超过累计核算金额（${this.accountingFunds || 0}万元）`,
              '提示',
              {
                confirmButtonText: '继续登记',
                cancelButtonText: '取消',
                type: 'warning',
              }
            )
              .then(() => {
                this.$refs.attachOss.submit()
              })
              .catch(() => {})
          } else {
            this.$refs.attachOss.submit()
          }
        } else {
          this.$message.error('输入错误，请重新输入')
        }
      })
    },
    async handleImagesComplete(images) {
      const imageStr = strFromOss(images)
      const formData = {
        ...this.ruleForm,
        attachment: imageStr,
        pay_status: 0,
      }

      try {
        this.saveLoading = true

        const id = this.editRow.id
        if (id) {
          await this.updateData(id, formData)
        } else {
          await this.addData({
            ...formData,
            due_warrant_date: this.collectRow.due_warrant_date,
            customer_related_id: this.collectRow.customer_related_id,
            order_no: this.collectRow.order_no,
            related_id: this.collectRow.id,
            submit_person_name: this.user.realName,
          })
        }

        this.$message.success(`保存成功`)
        this.$emit('success')
        this.beforeClose()
      } catch (error) {
        const messge =
          typeof error === 'object' && typeof error.data === 'object'
            ? error.data.error_description
            : ''
        this.$message.error(messge || `保存失败，请重试`)
      } finally {
        this.saveLoading = false
      }
    },
    addData(data) {
      return this.$api.addData({
        table: this.tableName,
        data,
      })
    },
    updateData(id, data) {
      return this.$api.updateData({
        table: this.tableName,
        id,
        data,
      })
    },
    // 获取项目所有登记的总金额
    getRegisterTotalFunds() {
      const relatedId = this.collectRow.customer_related_id
      if (!relatedId) return

      this.$api
        .getData({
          table: 'credit_warrant_fee_register',
          params: {
            'customer_related_id.eq': relatedId,
            'pay_status.eq': '',
            groupFunc: 'sum(credit_warrant_fee_register.actual_warrant_fee)',
          },
        })
        .then(res => {
          const data = res.data || []
          if (data.length) {
            this.registerTotalFunds = +(data[0].p || 0)
          }
        })
        .catch(() => {
          this.registerTotalFunds = 0
        })
    },
  },
}
</script>
<style lang="scss" scoped></style>
